package mujmail;

/*
MujMail - Simple mail client for J2ME
Copyright (C) 2006 Nguyen Son Tung <n.sontung@gmail.com>
Copyright (C) 2006 Martin Stefan <martin.stefan@centrum.cz>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import lcduilwuit.ChoiceGroup;
import lcduilwuit.TextField;
import lcduilwuit.Form;
import lcduilwuit.ItemStateListener;
import lcduilwuit.Command;
import lcduilwuit.Item;
import lcduilwuit.Choice;
import javax.microedition.lcdui.AlertType;
import javax.microedition.rms.RecordStore;
import mujmail.ordering.Criterion;
import mujmail.ordering.Ordering;
import java.util.Vector;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import java.util.Enumeration;
import com.sun.lwuit.CheckBox;
import com.sun.lwuit.*;
import mujmail.threading.Algorithm;
//#ifdef MUJMAIL_SSL
//# import mujmail.ui.SSLTypeChooser;
//#endif
public class Settings {

    /** Flag signals if we want to print debug prints */
    private static final boolean DEBUG = false;

    //determine actual settings format, change it always we modify settings format.
    //otherwise loading a different format will cause a crash!
    public final long SETTINGSVERSION = 20100312;

    
     private static int timezoneIndex;
     static final  float[] TIMEZONE_OFFSETTS={-12,-11,-10,-9,-8,-7,-6,-5,-4.5f,-4,-3.5f,-3,-2,-1,0,1,2,3,4,4.5f,5,5.5f,5.75f,6,6.5f,7,8,9,9.5f,10,11,12,13};
    
    public static final int FONT_NORMAL = 0;
    public static final int FONT_LARGE = 1;
    
    public static final int CONST_PORT_SMTP = 25;
    public static final int CONST_PORT_SMTPS = 465;
    
    public static long MAX_MAIL_SIZE_FOR_DOWNLOAD = 50 * 1024;
    public static long MAX_ATTACHMENT_SIZE_FOR_SENDING = 500 * 1000;

    Command back, ok;

      // TODO (betlista): next comment is correct, but it breaks good OOP design
    //all attributes are static for easier access from other classes, without
    //having a reference (mujMail.settings.)	
    
    public static final int fontSize = FONT_NORMAL;;
    public static final String notSetPE = "not_set.see@Accounts.menu";
    public static String primaryEmail;
    public static byte langId=0; //Anup
    public static final boolean downWholeMail=false;
    public static boolean downOnlyNeverSeen; //download only mails that were never seen in all seasons
    public static boolean checkMailWhenLaunch;
    public static boolean delMailFromServer;
    public static final boolean delOnExit=false;
    public static boolean addToAddressbook;
  //  public static final boolean smallFontMailForm=true;
    public static boolean replaceTabs;//if mailForm should display ' ' instead of '\t'
    public static final boolean moveToTrash = false; //use trash or not
    public static boolean safeMode; //recycles only one record store to store mail bodies
    public static String password = ""; /** Password that must be entered before mujMail starts. If empty, no password must be entered. */
    //public static short minInBoxDBSpace = -1; //auto clear inbox if out of DB space
    public static short maxMailsRetrieve; //how many mails should be downloaded once per an account
    public static short maxLinesRetrieve; //how many lines of a mail to retrieve
    /** The maximum size of bodypart. -1 means unlimited size. */
    private static long maxSizeOfBodypart;
    public static boolean pollDownloadsMails;
    public static boolean pollPlaysSound;
    public static int pollInvl; //polling interval in sec
    public static final int MIN_POLLING_INTERVAL = 5*60;
    public static int timeout; //communication timeout	
    public static String signature;
    public static final int noopPeriod = 1000 * 30; //a period in which protocols sends "noop" or its equivalent to keep connection alive
    public static final int noopIMAPPeriod = 1000 * 60 * 5; //noop period of IMAP 29minutes
    //represents sort modes of the boxes. 
    //the most right 4bits are for inBox sortMode, other 4bits are for draft, other 4 are for outBox, other 4 for sentBox
    //see more in the TheBox.sortMode comments
    public static int theBoxSortModes;
    //if debug is set to true most of alerts and information exchanged with server are printed to SYSTEM.OUT
    public static final boolean debug = false;

    /** Defines whether or not e-mail have to be ordered in threads. */
    public static final boolean threading = false;
    /* * Defines if the empty root messages for threads have to be shown. */
    //public static boolean rootsVisible;
    /** Automatically delete mails when headers database is full. */
    public static boolean deleteMailsWhenHeaderDBIsFull;
    /** Automatically delete body of mails when body database is full. */
    public static boolean deleteMailsBodyWhenBodyDBIsFull;

//#ifdef SONIMMAIL_CAMERA
    public static String defaultEmailSnapshot;
    public static String defaultSubjectSnapshot;
    public static boolean enableGeotagging;
    public static boolean startGPSinit;
 //#endif
    MujMail mujMail;
   // SortForm sortForm;

    /**
     * Gets maximum size of bodypart.
     * @return maximum size of bodypart.
     */
    public static long getMaxSizeOfBodypart() {
        if (maxSizeOfBodypart == -1) return Long.MAX_VALUE;

        return maxSizeOfBodypart;
    }

    /**
     * Loads default values of static variables.
     */
    private void loadDefaultValues() {
  //      fontSize = FONT_NORMAL;
        primaryEmail = notSetPE;
//        downWholeMail = false;
        downOnlyNeverSeen = true; //download only mails that were never seen in all seasons
        checkMailWhenLaunch = false;
        delMailFromServer = true;
    //    delOnExit = false;
        addToAddressbook = true;
//        smallFontMailForm = true;
        replaceTabs = true;//if mailForm should display ' ' instead of '\t'
//        moveToTrash = false; //use trash or not
        safeMode = false; //recycles only one record store to store mail bodies
        password = ""; /** Password that must be entered before mujMail starts. If empty, no password must be entered. */
        //public static short minInBoxDBSpace = -1; //auto clear inbox if out of DB space
        try {
            maxMailsRetrieve = (short)Integer.parseInt(MujMail.mujmail.getAppProperty("MAX-MAILS-RETRIEVE"));
        } catch (Exception e) {
            maxMailsRetrieve = 50; //how many mails should be downloaded once per an account
            e.printStackTrace();
        }
        try {
            MAX_MAIL_SIZE_FOR_DOWNLOAD = Integer.parseInt(MujMail.mujmail.getAppProperty("MAX-MAIL-SIZE-FOR-DOWNLOAD"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            MAX_ATTACHMENT_SIZE_FOR_SENDING = Integer.parseInt(MujMail.mujmail.getAppProperty("MAX-ATTACHMENT-SIZE-FOR-SENDING"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        maxLinesRetrieve = -1; //how many lines of a mail to retrieve
        /** The maximum size of bodypart. -1 means unlimited size. */
        maxSizeOfBodypart =Settings.MAX_MAIL_SIZE_FOR_DOWNLOAD;//100000;
        pollDownloadsMails = false;
        pollPlaysSound = true;
        pollInvl = MIN_POLLING_INTERVAL; //polling interval in sec
        timeout = 10 * 1000; //communication timeout
        signature = "";

        //represents sort modes of the boxes.
        //the most right 4bits are for inBox sortMode, other 4bits are for draft, other 4 are for outBox, other 4 for sentBox
        //see more in the TheBox.sortMode comments
        theBoxSortModes = 0;

      //  threading = false;
        deleteMailsWhenHeaderDBIsFull = false;
        deleteMailsBodyWhenBodyDBIsFull = false;
        timezoneIndex = 14;
        //#ifdef SONIMMAIL_CAMERA
        defaultEmailSnapshot="";
        defaultSubjectSnapshot="Snapshot taken from SonimMail";
        enableGeotagging=false;
        startGPSinit=false;
        //#endif
    }

    /**
     * Restores settings to default values.
     */
    public void restoreSettings() {
        loadDefaultValues();
        saveSettings(false);
        updateValuesToForms();
    }

    //#ifdef MUJMAIL_SYNC
//#     public String toString() {
//#     	StringBuffer sb = new StringBuffer();
//#     	sb.append("SettingsVersion: ").append(SETTINGSVERSION).append('\n');
//#     	sb.append("mujMailSrvAddr: ").append(mujMailSrvAddr).append('\n');
//#     	sb.append("mujMailSrvPort: ").append(mujMailSrvPort).append('\n');
//#     	sb.append("mujMailSrvLogin: ").append(mujMailSrvLogin).append('\n');
//#     	sb.append("primaryEmail: ").append(primaryEmail).append('\n');
//#     	sb.append("smtpServer: ").append(smtpServer).append('\n');
//#     	sb.append("smtpSSL: ").append((smtpSSL ? "1" : "0")).append('\n');
        //#ifdef MUJMAIL_SSL
//#         sb.append("smtpSSLType: ").append(smtpSSLType).append('\n');
        //#endif
//#     	sb.append("smtpPort: ").append(smtpPort).append('\n');
//#     	sb.append("smtpAuthName: ").append(smtpAuthName).append('\n');
//#     	sb.append("fontSize: ").append(fontSize).append('\n');
//#     	sb.append("downWholeMail: ").append((downWholeMail ? "1" : "0")).append('\n');
//#     	sb.append("downOnlyNeverSeen: ").append((downOnlyNeverSeen ? "1" : "0")).append('\n');
//#     	sb.append("delMailFromServer: ").append((delMailFromServer ? "1" : "0")).append('\n');
//#     	sb.append("delOnExit: ").append((delOnExit ? "1" : "0")).append('\n');
//#     	sb.append("addToAddressbook: ").append((addToAddressbook ? "1" : "0")).append('\n');
//#     	sb.append("smallFontMailForm: ").append((smallFontMailForm ? "1" : "0")).append('\n');
//#     	sb.append("replaceTabs: ").append((replaceTabs ? "1" : "0")).append('\n');
//#     	sb.append("moveToTrash: ").append((moveToTrash ? "1" : "0")).append('\n');
//#     	sb.append("safeMode: ").append((safeMode ? "1" : "0")).append('\n');
//#         sb.append("deleteMailsWhenHeaderDBIsFull: ").append((deleteMailsWhenHeaderDBIsFull ? "1" : "0")).append('\n');
//#         sb.append("deleteMailsBodyWhenBodyDBIsFull: ").append((deleteMailsBodyWhenBodyDBIsFull ? "1" : "0")).append('\n');
//#     	//sb.append("minInBoxDBSpace: ").append(minInBoxDBSpace).append('\n');
//#     	sb.append("maxMailsRetrieve: ").append(maxMailsRetrieve).append('\n');
//#     	sb.append("maxLinesRetrieve: ").append(maxLinesRetrieve).append('\n');
//#         sb.append("maxSizeOfBodypart: ").append(maxSizeOfBodypart).append('\n');
//#     	sb.append("pollPlaysSound: ").append((pollPlaysSound ? "1" : "0")).append('\n');
//#     	sb.append("pollDownloadsMails: ").append((pollDownloadsMails ? "1" : "0")).append('\n');
//#     	sb.append("pollInvl: ").append(pollInvl).append('\n');
//#     	sb.append("timeout: ").append(timeout).append('\n');
//#     	sb.append("theBoxSortModes: ").append(theBoxSortModes).append('\n');
//#     	sb.append("signature: ").append(signature).append("\n\n");		//NOTE: last line has to contain double newline
//#     	return sb.toString();
//#     }
    //#endif
    
    //#ifdef MUJMAIL_SYNC
//#     public void parseAndSetup(String setupStr)
//#     {
//#     	//skip SETTINGSVERSION for now
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	mujMailSrvAddr = setupStr.substring(setupStr.indexOf("mujMailSrvAddr: ") + 16, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	mujMailSrvPort = setupStr.substring(setupStr.indexOf("mujMailSrvPort: ") + 16, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	mujMailSrvLogin = setupStr.substring(setupStr.indexOf("mujMailSrvLogin: ") + 17, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	primaryEmail = setupStr.substring(setupStr.indexOf("primaryEmail: ") + 14, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	smtpServer = setupStr.substring(setupStr.indexOf("smtpServer: ") + 12, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	smtpSSL = "1".equals(setupStr.substring(setupStr.indexOf("smtpSSL: ") + 9, setupStr.indexOf('\n')));
        //#ifdef MUJMAIL_SSL
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#         smtpSSLType = Integer.valueOf(setupStr.substring(setupStr.indexOf("smtpSSLType: ") + 13, setupStr.indexOf('\n'))).byteValue();
        //#endif
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	smtpPort = Integer.valueOf(setupStr.substring(setupStr.indexOf("smtpPort: ") + 10, setupStr.indexOf('\n'))).shortValue();
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	smtpAuthName = setupStr.substring(setupStr.indexOf("smtpAuthName: ") + 14, setupStr.indexOf('\n'));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	fontSize = Integer.parseInt(setupStr.substring(setupStr.indexOf("fontSize: ") + 10, setupStr.indexOf('\n')));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	downWholeMail = "1".equals(setupStr.substring(setupStr.indexOf("downWholeMail: ") + 15, setupStr.indexOf('\n')));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	downOnlyNeverSeen = "1".equals(setupStr.substring(setupStr.indexOf("downOnlyNeverSeen: ") + 19, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	delMailFromServer = "1".equals(setupStr.substring(setupStr.indexOf("delMailFromServer: ") + 19, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	delOnExit = "1".equals(setupStr.substring(setupStr.indexOf("delOnExit: ") + 11, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	addToAddressbook = "1".equals(setupStr.substring(setupStr.indexOf("addToAddressbook: ") + 18, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	smallFontMailForm = "1".equals(setupStr.substring(setupStr.indexOf("smallFontMailForm: ") + 19, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	replaceTabs = "1".equals(setupStr.substring(setupStr.indexOf("replaceTabs: ") + 13, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	moveToTrash = "1".equals(setupStr.substring(setupStr.indexOf("moveToTrash: ") + 13, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	safeMode = "1".equals(setupStr.substring(setupStr.indexOf("safeMode: ") + 10, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#         deleteMailsWhenHeaderDBIsFull = "1".equals(setupStr.substring(setupStr.indexOf("deleteMailsWhenHeaderDBIsFull: ") + 31, setupStr.indexOf('\n')));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#         deleteMailsBodyWhenBodyDBIsFull = "1".equals(setupStr.substring(setupStr.indexOf("deleteMailsBodyWhenBodyDBIsFull: ") + 33, setupStr.indexOf('\n')));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	//minInBoxDBSpace = Integer.valueOf(setupStr.substring(setupStr.indexOf("minInBoxDBSpace: ") + 17, setupStr.indexOf('\n'))).shortValue();
//#     	//setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	maxMailsRetrieve = Integer.valueOf(setupStr.substring(setupStr.indexOf("maxMailsRetrieve: ") + 18, setupStr.indexOf('\n'))).shortValue();
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	maxLinesRetrieve = Integer.valueOf(setupStr.substring(setupStr.indexOf("maxLinesRetrieve: ") + 18, setupStr.indexOf('\n'))).shortValue();    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#         maxSizeOfBodypart = Long.parseLong(setupStr.substring(setupStr.indexOf("maxSizeOfBodypart: ") + 19, setupStr.indexOf('\n')));
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	pollPlaysSound = "1".equals(setupStr.substring(setupStr.indexOf("pollPlaysSound: ") + 16, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	pollDownloadsMails = "1".equals(setupStr.substring(setupStr.indexOf("pollDownloadsMails: ") + 20, setupStr.indexOf('\n')));    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	pollInvl = Integer.valueOf(setupStr.substring(setupStr.indexOf("pollInvl: ") + 10, setupStr.indexOf('\n'))).intValue();    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	timeout = Integer.valueOf(setupStr.substring(setupStr.indexOf("timeout: ") + 9, setupStr.indexOf('\n'))).intValue();    	
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	theBoxSortModes = Integer.valueOf(setupStr.substring(setupStr.indexOf("theBoxSortModes: ") + 17, setupStr.indexOf('\n'))).intValue();
//#     	setupStr = setupStr.substring(setupStr.indexOf('\n') + 1);
//#     	signature = setupStr.substring(setupStr.indexOf("signature: ") + 11, setupStr.indexOf('\n'));
//# 
//#     	  if (DEBUG) System.out.println("DEBUG Settings.parseAndSetup(String) - SETTINGS="+toString());
//#     	saveSettings(false);
//#     	mujMail.getMenu().refresh(Menu.SETTINGS, false);
//#     	loadSettings();
//#     }
    //#endif
    
    class SortForm extends Form implements ItemStateListener,ActionListener {

    	/** Index for the "threading enabled" option */
    //	private static final byte THREADING_ENABLED_CHACKBOX = 0;

        ChoiceGroup sortByCG;
        ChoiceGroup sortOrderCG;
        TheBox box;
      //  ChoiceGroup threadingGroup;

        public SortForm() {
            super(Lang.get(Lang.ST_SORT_SETTINGS));

            sortByCG = new ChoiceGroup(Lang.get(Lang.ST_SORT_BY), Choice.EXCLUSIVE);
            sortByCG.append(Lang.get(Lang.ST_SORT_TIME), null);
            sortByCG.append(Lang.get(Lang.ST_SORT_SUBJECT), null);
            sortByCG.append(Lang.get(Lang.ST_SORT_RECIPIENTS), null);
            sortByCG.append(Lang.get(Lang.ST_SORT_SENDER), null);
            sortByCG.append(Lang.get(Lang.ST_SORT_SIZE), null);

            sortOrderCG = new ChoiceGroup(Lang.get(Lang.ST_SORT_ORDER), Choice.EXCLUSIVE);
            sortOrderCG.append(Lang.get(Lang.EXTRA_OLDER_FIRST), null); // have to represent unnatural ordering
           sortOrderCG.append(Lang.get(Lang.EXTRA_NEWER_FIRST), null); // have to represent natural ordering

         //   threadingGroup = new ChoiceGroup( Lang.get( Lang.ST_THREADING), Choice.MULTIPLE );
              // this is why the value of THREADING_ENABLED_CHACKBOX is 0
         //   threadingGroup.append( Lang.get( Lang.ST_THREADING_ENABLE), null );
            //threadingGroup.setSelectedFlags( new boolean[] { Settings.threading } );//Adithya

            append(sortByCG);
         //   append(sortOrderCG);
        //Anup    append( threadingGroup );
            addCommand(back);
            addCommand(ok);

            setCommandListener(this);
            setItemStateListener( this );
        }

        public void setOrderingLabels( int selectedCriterion ) {
            /*switch ( selectedCriterion ) {
                case 0: // time
                    sortOrderCG.set(0, "older first", null);
                    sortOrderCG.set(1, "newer first", null);
                    break;
                case 1: // subject
                case 2: // recipients
                case 3: // sender
                    sortOrderCG.set(0, "alphabetically", null);
                    sortOrderCG.set(1, "reverse order", null);
                    break;
                case 4: // size
                    sortOrderCG.set(0, "smaller first", null);
                    sortOrderCG.set(1, "bigger first", null);
                    break;
            }*///Adithya
        }

        public void updateValuesToForm() {
            // threadingGroup.setSelectedFlags( new boolean[] { Settings.threading } ); //Adithya
        }

        /* ***********************
         *    listener method    *
         *************************/
        public void itemStateChanged(Item src) {
            if ( src == sortByCG ) {
        	    int selected = sortByCG.getSelectedIndex();
        	    setOrderingLabels( selected );
        	}
        }
        public void actionPerformed(ActionEvent ae) {
            if (ae.getCommand() == ok) {
                saveSortSettings(box, sortByCG.getSelectedIndex(), sortOrderCG.getSelectedIndex());
                final Enumeration enum1 = box.getStorage().getEnumeration();
                MessageHeader messageHeader;
                final Vector/*<MessageHeader>*/ messageHeaders = new Vector();
                while (enum1.hasMoreElements()) {
                    messageHeader = (MessageHeader) enum1.nextElement();
                    messageHeaders.addElement(messageHeader);
                }
                TheBox sortedBox = box;
                sortedBox.setStorage(mujmail.threading.Algorithm.getAlgorithm().invoke(messageHeaders));
                sortedBox.resort();
                if (sortedBox instanceof InBox) {
                    ((InBox) sortedBox).setCurFirstUnread();
                }
            }
            box.show();
        }
    }

    public Settings(MujMail mujMail) {
    	loadDefaultValues();
        this.mujMail = mujMail;
        back = new Command(Lang.get(Lang.BTN_BACK), Command.BACK, 0);
        ok = new Command(Lang.get(Lang.BTN_OK), Command.OK, 1);
        loadSettings();
    }
    
    //sets sortMode for all boxes
    public void initSortMode() {
          if (DEBUG) System.out.println("DEBUG Settings.initSortMode() - sort modes: " + Integer.toHexString( theBoxSortModes ) );
        //theBoxSortModes;
        int tmp = theBoxSortModes;
        mujMail.getSentBox().setOrdering( Ordering.valueOf( tmp & 0x1 ) );
        mujMail.getSentBox().setCriterion( Criterion.valueOf( (tmp & 0xE) >> 1 ) );
        //#ifdef MUJMAIL_SEARCH
        //mujMail.getSearchBox().setCriterion( Criterion.valueOf( tmp & 0xE ) );
        //#endif
        tmp = tmp >> 4;
        mujMail.outBox.setOrdering( Ordering.valueOf( tmp & 0x1 ) );
        mujMail.outBox.setCriterion( Criterion.valueOf( (tmp & 0xE) >> 1 ) );
        tmp = tmp >> 4;
        mujMail.draft.setOrdering( Ordering.valueOf( tmp & 0x1 ) );
        mujMail.draft.setCriterion( Criterion.valueOf( (tmp & 0xE) >> 1 ) );
        tmp = tmp >> 4;
        mujMail.getInBox().setOrdering( Ordering.valueOf( tmp & 0x1 ) );
        mujMail.getInBox().setCriterion( Criterion.valueOf( (tmp & 0xE) >> 1 ) );
        tmp = tmp >> 4;
        mujMail.getTrash().setOrdering( Ordering.valueOf( tmp & 0x1 ) );
        mujMail.getTrash().setCriterion( Criterion.valueOf( (tmp & 0xE) >> 1 ) );
    }

    public void saveSortSettings(final TheBox box,int sortBy,int sortOrder) {
        //get selected modes and recalculate sortMode
      //  int sortBy = sortForm.sortByCG.getSelectedIndex();
        box.setCriterion( Criterion.valueOf( sortBy ) );
     //   int sortOrder = sortForm.sortOrderCG.getSelectedIndex();
        box.setOrdering( Ordering.valueOf( sortOrder ) );
        TheBox tmpBox = mujMail.getTrash();
        theBoxSortModes = (tmpBox.getCriterion().ordinal << 1) + tmpBox.getOrdering().ordinal;
        tmpBox = mujMail.getInBox();
        theBoxSortModes = (theBoxSortModes << 4) + (tmpBox.getCriterion().ordinal << 1) + tmpBox.getOrdering().ordinal;
        tmpBox = mujMail.draft;
        theBoxSortModes = (theBoxSortModes << 4) + (tmpBox.getCriterion().ordinal << 1) + tmpBox.getOrdering().ordinal;
        tmpBox = mujMail.outBox;
        theBoxSortModes = (theBoxSortModes << 4) + (tmpBox.getCriterion().ordinal << 1) + tmpBox.getOrdering().ordinal;
        tmpBox = mujMail.getSentBox();
        theBoxSortModes = (theBoxSortModes << 4) + (tmpBox.getCriterion().ordinal << 1) + tmpBox.getOrdering().ordinal;

       // saveThreadingSettings();

        saveSettings(true);
    }

    /**
     * Saves settings for threading - whether the threading is enabled and when
     * it's enabled whether the empty root messages have to be shows.
     *  
     * @param box
     */
   /* private void saveThreadingSettings() {
    	  // assumes that THREADING_SHOW_ROOTS is the last check box index 
    	boolean[] selected = new boolean[SortForm.THREADING_ENABLED_CHACKBOX + 1];
    	//sortForm.threadingGroup.getSelectedFlags( selected );//Adithya

    	threading = selected[SortForm.THREADING_ENABLED_CHACKBOX];
    }*/

    public void showSortFrm(TheBox box) {
        SortForm sortForm = new SortForm();
        sortForm.box = box;
        sortForm.sortOrderCG.setSelectedIndex(box.getOrdering().ordinal, true);
        sortForm.sortByCG.setSelectedIndex(box.getCriterion().ordinal, true);
        sortForm.setOrderingLabels( box.getCriterion().ordinal );
        mujMail.getDisplay().setCurrent(sortForm);
    }

    /**
     * Updates values of settings variables to forms that displays settings.
     */
    public void updateValuesToForms() {
     if(retrievingSettingsForm!=null)
        retrievingSettingsForm.updateValuesToForm();
     if(otherSettingsForm!=null)
        otherSettingsForm.updateValuesToForm();
     if(storingSettingsForm!=null)
        storingSettingsForm.updateValuesToForm();
     if(pollingSettingsForm!=null)
        pollingSettingsForm.updateValuesToForm();
     //#ifdef SONIMMAIL_CAMERA
     if(snapshotSettingsForm!=null)
        snapshotSettingsForm.updateValuesToForm();
     //#endif
    }

    public void saveSettings(boolean init) {
          if (DEBUG) System.out.println("DEBUG Settings.saveSettings(boolean " + init + ")");
        // initialize variables
    	if (init) {
	        try {
                if(retrievingSettingsForm!=null)
                retrievingSettingsForm.updateValuesFromForm();
                if(otherSettingsForm!=null)
                otherSettingsForm.updateValuesFromForm();
                if(storingSettingsForm!=null)
                storingSettingsForm.updateValuesFromForm();
                if(pollingSettingsForm!=null)
                pollingSettingsForm.updateValuesFromForm();
                //#ifdef SONIMMAIL_CAMERA
                if(snapshotSettingsForm!=null)
                snapshotSettingsForm.updateValuesFromForm();
                //#endif
	        } catch (Exception ex) { //bad input may occur, empty port fields..
	            ex.printStackTrace();
	            updateValuesToForms(); //set defaults
	            mujMail.alert.setAlert(this,mujMail.getMenu(), Lang.get(Lang.ALRT_ST_SAVING) + Lang.get(Lang.FAILED), MyAlert.DEFAULT, AlertType.ERROR);
	            //return;
	        } 
    	}
          System.out.println("deleteMailsWhenHeaderDBIsFull: " + deleteMailsWhenHeaderDBIsFull);

        // save to RecordStore
        RecordStore rs;
        try {
            rs = RecordStore.openRecordStore("SETTINGS", true);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            DataOutputStream stream = new DataOutputStream(buffer);

            stream.writeLong(SETTINGSVERSION);
            
            stream.writeUTF(primaryEmail);
            //stream.writeInt(fontSize);
            //stream.writeBoolean(downWholeMail);
            stream.writeBoolean(downOnlyNeverSeen);
            stream.writeBoolean(checkMailWhenLaunch);
            stream.writeBoolean(delMailFromServer);
      //      stream.writeBoolean(delOnExit);
            stream.writeBoolean(addToAddressbook);
      //      stream.writeBoolean(smallFontMailForm);
            stream.writeBoolean(replaceTabs);
    //        stream.writeBoolean(moveToTrash);
            stream.writeBoolean(safeMode);
            stream.writeBoolean(deleteMailsWhenHeaderDBIsFull);
            stream.writeBoolean(deleteMailsBodyWhenBodyDBIsFull);
            //stream.writeShort(minInBoxDBSpace);
            stream.writeShort(maxMailsRetrieve);
            stream.writeShort(maxLinesRetrieve);
            stream.writeLong(maxSizeOfBodypart);
            stream.writeBoolean(pollPlaysSound);
            stream.writeBoolean(pollDownloadsMails);
            stream.writeInt(pollInvl);
            stream.writeInt(timeout);
            stream.writeInt(theBoxSortModes);
            stream.writeUTF(signature);
            stream.writeUTF(password);

              // save the threading settings
         //   stream.writeBoolean( threading );
             stream.writeInt(timezoneIndex);
             //#ifdef SONIMMAIL_CAMERA
             stream.writeUTF(defaultEmailSnapshot);
             stream.writeUTF(defaultSubjectSnapshot);
             stream.writeBoolean(enableGeotagging);
             stream.writeBoolean(startGPSinit);
              //#endif
          //  stream.writeByte( langId );//anup
            if (Lang.getCurrentLanguage() != langId)
            {
                mujMail.alert.setAlert(this,mujMail.getMenu(), Lang.get(Lang.EXTRA_LAN_SETTING_EFFECT_REBOOT), MyAlert.DEFAULT, AlertType.WARNING);
            }
            Lang.saveLang();
            stream.flush();
            if (rs.getNumRecords() == 1) {
                rs.setRecord(1, buffer.toByteArray(), 0, buffer.size());
            } else {
                rs.addRecord(buffer.toByteArray(), 0, buffer.size());
            }
            rs.closeRecordStore();
          //  if (mujMail.getDisplay().getCurrent() != mujMail.mailForm) {
            if(!(mujMail.getDisplay().getCurrent() instanceof MailForm)){
                mujMail.mainMenu();
            }
        } catch (Exception e) {
            e.printStackTrace();
            mujMail.alert.setAlert(this,mujMail.getMenu(), Lang.get(Lang.ALRT_ST_SAVING) + Lang.get(Lang.FAILED), MyAlert.DEFAULT, AlertType.ERROR);
            return;
        }
    }

    /**
     * This is called only at the beginning in the mujMail.startApp() method.
     */
    public void loadSettings() {
          if (DEBUG) System.out.println("DEBUG Setting.loadSettings()");
        // load from the RecordStore
        RecordStore rs;
        try {
            rs = RecordStore.openRecordStore("SETTINGS", true);
            // settings has already been saved
            if (rs.getNumRecords() == 1) {
                  if (DEBUG) System.out.println("DEBUG Settings.loadSettings() - loading settings");
                ByteArrayInputStream buffer = new ByteArrayInputStream(rs.getRecord(1));
                DataInputStream stream = new DataInputStream(buffer);

                long sv = stream.readLong();
                if (sv != this.SETTINGSVERSION) { //previous settings format is different
                    rs.closeRecordStore();
                    updateValuesToForms();
                    saveSettings(true); //create new format;
                    return; //otherwise it may cause a crash if we read different format
                }
               
                primaryEmail = stream.readUTF();
//                fontSize = stream.readInt();
//                downWholeMail = stream.readBoolean();
                downOnlyNeverSeen = stream.readBoolean();
                checkMailWhenLaunch = stream.readBoolean();
                delMailFromServer = stream.readBoolean();
      //          delOnExit = stream.readBoolean();
                addToAddressbook = stream.readBoolean();
     //           smallFontMailForm = stream.readBoolean();
                replaceTabs = stream.readBoolean();
  //              moveToTrash = stream.readBoolean();
                safeMode = stream.readBoolean();
                deleteMailsWhenHeaderDBIsFull = stream.readBoolean();
                deleteMailsBodyWhenBodyDBIsFull = stream.readBoolean();
                //minInBoxDBSpace = stream.readShort();
                maxMailsRetrieve = stream.readShort();
                maxLinesRetrieve = stream.readShort();
                maxSizeOfBodypart = stream.readLong();
                pollPlaysSound = stream.readBoolean();
                pollDownloadsMails = stream.readBoolean();
                pollInvl = stream.readInt();
                timeout = stream.readInt();
                theBoxSortModes = stream.readInt();
                signature = stream.readUTF();
                password = stream.readUTF();

             //   threading = stream.readBoolean();
                timezoneIndex = stream.readInt();
                //langId = stream.readByte();//anup
                //#ifdef SONIMMAIL_CAMERA
                defaultEmailSnapshot=stream.readUTF();
                defaultSubjectSnapshot=stream.readUTF();
                enableGeotagging=stream.readBoolean();
                startGPSinit=stream.readBoolean();
                //#endif
                Lang.loadSavedLang();
                
                rs.closeRecordStore();
                  if (DEBUG) System.out.println("DEBUG Settings.loadSettings() - loading settings..successful");
            }
        } catch (Exception e) {
            e.printStackTrace();
            mujMail.alert.setAlert(this,mujMail.getMenu(), Lang.get(Lang.ALRT_ST_LOADING) + Lang.get(Lang.FAILED), MyAlert.DEFAULT, AlertType.ERROR);
        }
        updateValuesToForms();
    }

     private static RetrievingSettingsForm retrievingSettingsForm;
    public void showRetrievingSettingsForm() {
        retrievingSettingsForm = new RetrievingSettingsForm();
        retrievingSettingsForm.updateValuesToForm();
        mujMail.getDisplay().setCurrent(retrievingSettingsForm);
    }
    private static StoringSettingsForm storingSettingsForm;
    public void showStoringMailsSettingsForm() {
        storingSettingsForm = new StoringSettingsForm();
        storingSettingsForm.updateValuesToForm();
        mujMail.getDisplay().setCurrent(storingSettingsForm);
    }

    private static PollingSettingsForm pollingSettingsForm;
    public void showPollingSettingsForm() {
        pollingSettingsForm = new PollingSettingsForm();
        pollingSettingsForm.updateValuesToForm();
        mujMail.getDisplay().setCurrent(pollingSettingsForm);
    }

    private static OtherSettingsForm otherSettingsForm;
    public void showOtherSettingsForm() {
        otherSettingsForm = new OtherSettingsForm();
        otherSettingsForm.updateValuesToForm();
        mujMail.getDisplay().setCurrent(otherSettingsForm);
    }
    //#ifdef SONIMMAIL_CAMERA
    private static SnapshotSettingsForm snapshotSettingsForm;
   
    public void showSnaphotSettingsForm(){
        snapshotSettingsForm = new SnapshotSettingsForm();
        snapshotSettingsForm.updateValuesToForm();
        mujMail.getDisplay().setCurrent(snapshotSettingsForm);
    }
     //#endif
    /**
     * Represents the form that displays settins variables.
     */
    private abstract class SettingsForm extends Form implements ActionListener {
        public SettingsForm(String title) {
            super(title);
            addCommand(back);
            addCommand(ok);
            setCommandListener(this);
                
           }
           public void actionPerformed(ActionEvent ae) {
            com.sun.lwuit.Command c = ae.getCommand();
            if (c == back) {
                loadSettings();
                unloadAllSettingsForm();
                mujMail.mainMenu();
            } else if (c == ok) {
                saveSettings(true);
                unloadAllSettingsForm();
            }
        }

        /**
         * Displays values of settings variables in the form.
         */
        protected abstract void updateValuesToForm();
        /**
         * Update values of settings variable according to values in form.
         */
        protected abstract void updateValuesFromForm() throws Exception;

    }
    private class RetrievingSettingsForm extends SettingsForm {
        private ChoiceGroup retrievingSettingsChG;
        TextField maxMailsTF;
        TextField maxLinesTF;
        TextField maxSizeOfBodyPartTF;
        public void actionPerformed(ActionEvent ae)
        {
            if (ae.getCommand() == ok) {
                int maxMail = 0, maxBp = 1;
                try {
                    maxMail = Integer.parseInt(maxMailsTF.getString());
                    maxBp = Integer.parseInt(maxSizeOfBodyPartTF.getString());
                } catch (Exception e) {
                    maxMail = -1;
                }
                if (maxMail != -1 && (maxMail > 100 || maxMail < 1)) {
                    com.sun.lwuit.Dialog.show("",maxMailsTF.getLabel()+" "+ Lang.get(Lang.EXTRA_SHOULD_BE_BETWEEN)+" " + 100, "OK", "");
                    maxMailsTF.setString(""+maxMailsRetrieve);
                    return;
                }
                if (maxBp > Settings.MAX_MAIL_SIZE_FOR_DOWNLOAD || maxBp < 1) {
                    com.sun.lwuit.Dialog.show("",maxSizeOfBodyPartTF.getLabel()+" "+ Lang.get(Lang.EXTRA_SHOULD_BE_BETWEEN)+" " + Settings.MAX_MAIL_SIZE_FOR_DOWNLOAD, "OK", "");
                    maxSizeOfBodyPartTF.setString(String.valueOf(MAX_MAIL_SIZE_FOR_DOWNLOAD));
                    return;
                }
            }
            super.actionPerformed(ae);
        }
        public RetrievingSettingsForm() {
            super(Lang.get(Lang.EXTRA_RETRIVIEVING_MAILS_SETTING));
            retrievingSettingsChG = new ChoiceGroup("", Choice.MULTIPLE);
          //  retrievingSettingsChG.append(Lang.get(Lang.ST_DOWN_WHOLE_MAIL), null);
            retrievingSettingsChG.append(Lang.get(Lang.ST_DOWNLOAD_ONLY_NEVER_SEEN), null);
            retrievingSettingsChG.append(Lang.get(Lang.EXTRA_RECEIVE_MAIL_WHEN_LAUNCH),null);
            maxMailsTF = new TextField(Lang.get(Lang.ST_RETR_MAX_MAILS), String.valueOf(maxMailsRetrieve), 3, TextField.NUMERIC);
        }

        protected void updateValuesFromForm() {
           // downWholeMail = retrievingSettingsChG.isSelected(0);
            downOnlyNeverSeen = retrievingSettingsChG.isSelected(0);
            checkMailWhenLaunch =  retrievingSettingsChG.isSelected(1);
            maxMailsRetrieve = Short.parseShort(maxMailsTF.getString());
            maxLinesRetrieve = Short.parseShort(maxLinesTF.getString());
            maxSizeOfBodypart = Long.parseLong(maxSizeOfBodyPartTF.getString());
        }

        protected void updateValuesToForm() {
           // retrievingSettingsChG.setSelectedIndex(0, downWholeMail);
            retrievingSettingsChG.setSelectedIndex(0, downOnlyNeverSeen);
             retrievingSettingsChG.setSelectedIndex(1, checkMailWhenLaunch);

            maxLinesTF = new TextField(Lang.get(Lang.ST_RETR_MAX_LINES), String.valueOf(maxLinesRetrieve), 1000, TextField.NUMERIC);

            maxSizeOfBodyPartTF = new TextField(Lang.get(Lang.EXTRA_MAX_SIZE_BODYPART), String.valueOf(maxSizeOfBodypart), 10, TextField.NUMERIC);
            maxMailsTF.setString(String.valueOf(maxMailsRetrieve));
            deleteAll();
            append(retrievingSettingsChG);
            append(maxMailsTF);
            append(maxLinesTF);
            append(maxSizeOfBodyPartTF);
           
        }
    }
     public static int getGMTOffset()
        {
            return (int)(TIMEZONE_OFFSETTS[timezoneIndex]*(float)(60*60*1000));
        }
    private class OtherSettingsForm extends SettingsForm {

        private ChoiceGroup otherSettingsChG;
        private ChoiceGroup languageChG; //Anup
        private ChoiceGroup timezoneCG;
        TextField timeoutTF;
        TextField signatureTF;
        TextField passwordTF;


        public OtherSettingsForm() {
            super(Lang.get(Lang.EXTRA_OTHER_SETTINGS));
            languageChG = new ChoiceGroup(Lang.get(Lang.EXTRA_LANGUAGE),Choice.POPUP);
            String[] langs=Lang.getAvaliableLanguages();
            for(int i=0;i<langs.length;i++)
                languageChG.append(langs[i], null);
            otherSettingsChG = new ChoiceGroup("", Choice.MULTIPLE);
            otherSettingsChG.append(Lang.get(Lang.ST_DEL_FROM_SERVER), null);
    //        otherSettingsChG.append(Lang.get(Lang.ST_DEL_ON_EXIT), null);
            otherSettingsChG.append(Lang.get(Lang.ST_ADD_TO_ADBOOK), null);
            otherSettingsChG.append(Lang.get(Lang.ST_REPLACE_TABS), null);
    //        otherSettingsChG.append(Lang.get(Lang.ST_MOVE_TO_TRASH), null);
            Vector timezoneitems=new Vector();
            for(int i=0;i<TIMEZONE_OFFSETTS.length;i++)
            {
                float offset = TIMEZONE_OFFSETTS[i];
                StringBuffer str = new StringBuffer(Lang.get(Lang.EXTRA_GMT));
                str.append(offset>=0?'+':'-');
                if(Math.abs((int)offset)<=9)
                    str.append("0");
                 str.append(Integer.toString(Math.abs((int)offset)));
                 str.append(':');
                 offset=Math.abs(offset);
                 String last =String.valueOf((int)((offset-(int)offset)*60f));
                 str.append(last.length()==1?"0"+last:last);
                timezoneitems.addElement(str.toString());
            }
            timezoneCG = new ChoiceGroup(Lang.get(Lang.EXTRA_YOUR_TIMEZONE), timezoneitems);
          
        }


        protected void updateValuesFromForm() {
            delMailFromServer = otherSettingsChG.isSelected(0);
     //       delOnExit = otherSettingsChG.isSelected(1);
            addToAddressbook = otherSettingsChG.isSelected(1);
            replaceTabs = otherSettingsChG.isSelected(2);
  //          moveToTrash = otherSettingsChG.isSelected(3);

            timeout = Integer.parseInt(timeoutTF.getString());
            signature = signatureTF.getString();
            password = passwordTF.getString();
            langId = (byte)languageChG.getSelectedIndex(); //anup
            //minInBoxDBSpace = Short.parseShort(minInBoxDBSpaceTF.getString());
            timezoneIndex = timezoneCG.getSelectedIndex();
        }

        protected void updateValuesToForm() {
            languageChG.setSelectedIndex(langId,true); //anup //Adithya
            otherSettingsChG.setSelectedIndex(0, delMailFromServer);
       //     otherSettingsChG.setSelectedIndex(1, delOnExit);
            otherSettingsChG.setSelectedIndex(1, addToAddressbook);
            otherSettingsChG.setSelectedIndex(2, replaceTabs);
   //         otherSettingsChG.setSelectedIndex(3, moveToTrash);
            timezoneCG.setSelectedIndex(timezoneIndex,true);
            //minInBoxDBSpaceTF = new TextField(Lang.get(Lang.ST_AUTO_CLEAR_INBOX), String.valueOf(minInBoxDBSpace), 1000, TextField.NUMERIC);

           /*timeoutTF.setString(String.valueOf(timeout));
           signatureTF.setString(signature);
           passwordTF.setString(password);*/
            timeoutTF = new TextField(Lang.get(Lang.ST_TIMEOUT), String.valueOf(timeout), 1000, TextField.NUMERIC);
            signatureTF = new TextField(Lang.get(Lang.ST_SIGN), signature, 1000, TextField.ANY);
            passwordTF = new TextField(Lang.get(Lang.EXTRA_PASSWORD), password, 1000, TextField.PASSWORD);
             deleteAll();
            append(languageChG); //anup //Adithya
          
            append(otherSettingsChG);
            //append(minInBoxDBSpaceTF);
            append(timeoutTF);
            append(signatureTF);
            append(passwordTF);
            append(timezoneCG);
          
        }
    }
    
    private class StoringSettingsForm extends SettingsForm {
    private ChoiceGroup storingMailsSettingsChG;

        public StoringSettingsForm() {
            super(Lang.get(Lang.EXTRA_STORING_MAIL_SETTINGS));

            storingMailsSettingsChG = new ChoiceGroup("", Choice.MULTIPLE);
            storingMailsSettingsChG.append(Lang.get(Lang.ST_SAFE_MODE), null);
            storingMailsSettingsChG.append(Lang.get(Lang.EXTRA_DELETE_MAILS_CANNOT_SAVE_HEADER), null);
            storingMailsSettingsChG.append(Lang.get(Lang.EXTRA_DELETEBODYPART_CANNOT_SAVE_BODYPART), null);

            append(storingMailsSettingsChG);
        }

        protected void updateValuesFromForm() {
            safeMode = storingMailsSettingsChG.isSelected(0);
            deleteMailsWhenHeaderDBIsFull = storingMailsSettingsChG.isSelected(1);
            deleteMailsBodyWhenBodyDBIsFull = storingMailsSettingsChG.isSelected(2);
        }

        protected void updateValuesToForm() {
            storingMailsSettingsChG.setSelectedIndex(0, safeMode);
            storingMailsSettingsChG.setSelectedIndex(1, deleteMailsWhenHeaderDBIsFull);
            storingMailsSettingsChG.setSelectedIndex(2, deleteMailsBodyWhenBodyDBIsFull);
        }
    }
    
    private class PollingSettingsForm extends SettingsForm {
        ChoiceGroup pollCG;
        TextField pollInvlTF;
        public PollingSettingsForm() {
            super("Polling settings");

            pollCG = new ChoiceGroup(Lang.get(Lang.ST_POLLING_BEHAVIOUR), Choice.MULTIPLE);
            pollCG.append(Lang.get(Lang.ST_POLLING_PLAY_SOUND), null);
            pollCG.append(Lang.get(Lang.ST_POLLING_DOWN), null);
            pollInvlTF = new TextField(Lang.get(Lang.ST_POLLING_INTERVAL), String.valueOf(pollInvl), 1000, TextField.NUMERIC);
        }
        public void actionPerformed(ActionEvent ae)
        {
            if (ae.getCommand() == ok) {
                int value = 0;
                try {
                    value = Integer.parseInt(pollInvlTF.getString());
                } catch (Exception e) {
                }
                if (value < MIN_POLLING_INTERVAL) {
                    com.sun.lwuit.Dialog.show("", Lang.get(Lang.EXTRA_POLLING_INTERVAL_MUST_BE) + " " + MIN_POLLING_INTERVAL, Lang.get(Lang.BTN_OK), "");
                    pollInvlTF.setString(String.valueOf(MIN_POLLING_INTERVAL));
                    return;
                }
            }
            super.actionPerformed(ae);
        }
        protected void updateValuesToForm() {
            pollInvlTF.setString(String.valueOf(pollInvl));
            pollCG.setSelectedIndex(0, pollPlaysSound);
            pollCG.setSelectedIndex(1, pollDownloadsMails);
            deleteAll();
            append(pollInvlTF);
            append(pollCG);
        }

        protected void updateValuesFromForm() throws NumberFormatException {
            pollPlaysSound = pollCG.isSelected(0);
            pollDownloadsMails = pollCG.isSelected(1);
            pollInvl = Integer.parseInt(pollInvlTF.getString());
        }
    }

    public void unloadAllSettingsForm() {
        retrievingSettingsForm = null;
        otherSettingsForm = null;
        storingSettingsForm = null;
        pollingSettingsForm = null;
        //#ifdef SONIMMAIL_CAMERA
        snapshotSettingsForm = null;
        //#endif
        System.gc();
    }
    //#ifdef SONIMMAIL_CAMERA
    private class SnapshotSettingsForm extends SettingsForm{
        TextField defaultDestinationEmail;
        TextField defaultSubject;
        CheckBox enableGeotaggingCB;
        CheckBox statrtGPSStartupCB;
        public SnapshotSettingsForm() {
            super("Snapshot Setting");
            defaultDestinationEmail = new TextField("Default email to send photo",defaultEmailSnapshot,1000,TextField.EMAILADDR);
            defaultSubject = new TextField("Default subject",defaultSubjectSnapshot,1000,TextField.ANY);
            enableGeotaggingCB =  new CheckBox("Enable geotagging");
            enableGeotaggingCB.setSelected(enableGeotagging);
            statrtGPSStartupCB = new CheckBox("Start GPS when application launch.");
            statrtGPSStartupCB.setSelected(startGPSinit);
            enableGeotaggingCB.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent ae) {
                    if(enableGeotaggingCB.isSelected()){
                        addComponent(statrtGPSStartupCB);
                    }else{
                        startGPSinit=false;
                        GPSStuff.switchOffGPS();
                        statrtGPSStartupCB.setSelected(startGPSinit);
                        removeComponent(statrtGPSStartupCB);
                    }
                    revalidate();
                }

            });
            statrtGPSStartupCB.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent ae) {
                    if (statrtGPSStartupCB.isSelected()) {
                        try {
                            GPSStuff.getInstance();
                        } catch (SecurityException se) {
                            com.sun.lwuit.Dialog.show("Exception", "Couldnt start GPS, Please give permission", "OK", "");
                        } catch (Exception le) {
                            com.sun.lwuit.Dialog.show("Exception", "Couldnt start GPS: " + le, "OK", "");
                        }
                    } else {
                        GPSStuff.switchOffGPS();
                    }
                }
            });




        }

        protected void updateValuesToForm(){
            deleteAll();
            append(defaultDestinationEmail);
            append(defaultSubject);
            addComponent(enableGeotaggingCB);
            if(enableGeotagging){
                addComponent(statrtGPSStartupCB);
            }
        }

        protected void updateValuesFromForm() {
            defaultEmailSnapshot=defaultDestinationEmail.getString();
            defaultSubjectSnapshot=defaultSubject.getString();
            enableGeotagging = enableGeotaggingCB.isSelected();
            startGPSinit=statrtGPSStartupCB.isSelected();
        }

    }
    //#endif
}
